package com.ly.project_jt.controller;

import com.ly.project_jt.mapper.ItemMapper;
import com.ly.project_jt.pojo.Item;
import com.ly.project_jt.pojo.ItemExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/item")
public class ItemController {
    @Autowired
    ItemMapper itemMapper;

    //修改商品
    //localhost:1314/item/update?itemId=2&itemName=华为手机&itemPrice=999&itemDesc=aa&itemImage=2.jpg&categoryId=2
    @RequestMapping("/update")
    @CrossOrigin
    public String update(Item item){
        int rowCount=itemMapper.updateByPrimaryKey(item);
        if (rowCount>=1){
            return "修改成功！";
        }else{
            return "修改失败！";
        }
    }

    //删除商品
    @RequestMapping("/delete")
    @CrossOrigin
    public String delete(Integer itemId){
        int rowCount=itemMapper.deleteByPrimaryKey(itemId);
        if (rowCount>=1){
            return "删除成功！";
        }else {
            return "删除失败！";
        }
    }

    //查询所有商品
    //localhost:1314/item/selectAll
    @RequestMapping("/selectAll")
    @CrossOrigin
    public List<Item> selectAll(){
        return itemMapper.selectByExample(null);
    }

    //根据商品分类的id查询商品
    @RequestMapping("/findByCategoryId")
    @CrossOrigin
    public List<Item> findByCategoryId(Integer categoryId) {
        //select * from Item where category_id=1
        ItemExample itemExample = new ItemExample();
        ItemExample.Criteria criteria = itemExample.or();//or生成查询条件
        criteria.andCategoryIdEqualTo(categoryId);
        return itemMapper.selectByExample(itemExample);
    }

    //根据商品的编号查询商品
    //localhost:1314/item/findByItemId
    @RequestMapping("/findByItemId")
    @CrossOrigin
    public Item findByItemId(Integer itemId) {
        //根据主键查询
        Item item = itemMapper.selectByPrimaryKey(itemId);
        return item;
    }

    //添加商品
    //localhost:1314/item/insert?itemName=华为手机&categoryId=1&itemPrice=99&itemDesc=好&itemImage=1.jpg
    @RequestMapping("/insert")
    @CrossOrigin
    public String insert(Item item) {
        int rowCount = itemMapper.insert(item);
        if (rowCount >= 1) {
            return "添加成功！";
        } else {
            return "添加失败！";
        }
    }

}